﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.Caching;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Principal;

namespace BusinessLogic
{
  public class BizObject
  {
    public const int MAXROWS = int.MaxValue;
    public static Cache Cache
    {
      get { return HttpContext.Current.Cache; }
    }

    public static IPrincipal CurrentUser
    {
      get { return HttpContext.Current.User; }
    }

    public static string CurrentUserName
    {
      get
      {
        string userName = "";
        if (HttpContext.Current.User.Identity.IsAuthenticated)
          userName = HttpContext.Current.User.Identity.Name;
        return userName;
      }
    }

    public static string CurrentUserIP
    {
      get { return HttpContext.Current.Request.UserHostAddress; }
    }

    public static int GetPageIndex(int startRowIndex, int maximumRows)
    {
      if (maximumRows <= 0)
        return 0;
      else
        return (int)Math.Floor((double)startRowIndex / (double)maximumRows);
    }

    public static string ConvertNullToEmptyString(string input)
    {
      return (input == null ? "" : input);
    }

    /// <summary>
    /// Remove from the ASP.NET cache all items whose key starts with the input prefix
    /// </summary>
    public static void PurgeCacheItems(string prefix)
    {
      prefix = prefix.ToLower();
      List<string> itemsToRemove = new List<string>();

      IDictionaryEnumerator enumerator = BizObject.Cache.GetEnumerator();
      while (enumerator.MoveNext())
      {
        if (enumerator.Key.ToString().ToLower().StartsWith(prefix))
          itemsToRemove.Add(enumerator.Key.ToString());
      }
      foreach (string itemToRemove in itemsToRemove)
        BizObject.Cache.Remove(itemToRemove);
    }
    public static string Culture()
    {
      return HttpContext.Current.Profile.GetPropertyValue("Culture").ToString();
    }
    public static void CacheData(string key, object data)
    {
        if (data != null)
        {
            BizObject.Cache.Insert(key, data, null,
               DateTime.Now.AddSeconds(600), TimeSpan.Zero);
        }
    }
    public static void ClearCacheData()
    {
        List<string> itemsToRemove = new List<string>();
        IDictionaryEnumerator enumerator = BizObject.Cache.GetEnumerator();
        while (enumerator.MoveNext())
        {
            BizObject.Cache.Remove(enumerator.Key.ToString());
        }
    }
  }
}